﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Xml;

namespace omaura_oled
{
    /// <summary>
    /// Class for the access of weather data
    /// </summary>
    public class WeatherReader
    {
        #region "Parameters"
        //--
        private OmauraOled ParentOled;
        //--
        public string City;
        private string CityId;
        private int TemperatureSign;
        public int Temperature;
        public int WeatherIcon;
        //--
        private string PathToWeatherFile = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\omaura\\omaura oled\\Weather.txt";
        public string PathToWeatherImages = ".\\Resources\\Weather\\";
        //--
        public string WeatherID = "1059963103";
        public string WeatherKey = "bd91a14664235d69";
        //--
        #endregion "Parameters"

        #region "Constructors"
        //--
        public WeatherReader(OmauraOled Parent)
        {
            ParentOled = Parent;

            ReadWeather();
        }
        //--
        #endregion "Constructors"

        #region "Methods"
        //--
        public void ReadWeather()//(string pathToFile)
        {
            int i = 0;
            string firstPara;
            string line;

            //using (StreamReader fileReader = new StreamReader(".\\Resources\\Themes\\Current\\config.ini"))
            using (StreamReader fileReader = new StreamReader(PathToWeatherFile))
            {
                while (((line = fileReader.ReadLine()) != null) && i < 255)
                {
                    i++;

                    firstPara = line[0].ToString();
                    for (int charI = 1; charI < 4; charI++)
                        firstPara += line[charI].ToString();

                    //-- City
                    if (firstPara == "City")
                    {
                        int iCity = 8;
                        City = "";
                        while (line[iCity] != '|')
                        {
                            City += line[iCity];
                            iCity++;
                        }
                        ParentOled.labelTWeatherCityCurrent.Content = City;
                    }
                    if (firstPara == "CiId")
                    {
                        int iCity = 8;
                        CityId = "";
                        while (line[iCity] != '|')
                        {
                            CityId += line[iCity];
                            iCity++;
                        }
                    }

                    //-- Temperature
                    if (firstPara == "Temp")
                        Temperature = Convert.ToInt32(Convert.ToString(line[7]) + Convert.ToString(line[8]));
                    if (firstPara == "TSig")
                        TemperatureSign = Convert.ToInt32(Convert.ToString(line[7]));

                    //-- Temperature
                    if (firstPara == "Weat")
                        WeatherIcon = Convert.ToInt32(Convert.ToString(line[7]));
                }
            }
        }
        /// <summary>
        /// old
        /// </summary>
        /// <param name="Display"></param>
        public void WeatherDisplay(DisplayClass Display)
        {
            //-- display city
            Display.displayCity(City);

            //-- display temperature
            Display.displayTemperature(Temperature);

            //-- display weather
            if (WeatherIcon < 10)
                Display.displayLogo(PathToWeatherImages + "0" + WeatherIcon + ".bmp", 191, 6);
            else
                Display.displayLogo(PathToWeatherImages + WeatherIcon + ".bmp", 191, 6);
                
        }
        //--
        public void SaveWeather(string cityId, string cityName)
        {
            // Create a new file 
            // - copy the content of config.ini in this new file
            // - modify the parameters required
            // - erase the config.ini file by the modified one
            int i = 0;
            string line;
            string firstPara;
            string lineTemp = "";

            #region "Create temp file"
            //--
            using (StreamReader fileReader = new StreamReader(PathToWeatherFile, Encoding.Default))
            {
                // read line by line 
                // - if line contain parameters to modify: modify line and copy it
                // - if not just copy
                while (((line = fileReader.ReadLine()) != null) && i < 255)
                {
                    i++;

                    firstPara = line[0].ToString();
                    for (int charI = 1; charI < 4; charI++)
                        firstPara += line[charI].ToString();

                    #region "City"
                    //--
                    if (firstPara == "City")
                        lineTemp = "City = |" + cityName + "|";
                    else if (firstPara == "CiId")
                        lineTemp = "CiId = |" + cityId + "|";
                    //--
                    #endregion "City"

                    // else line
                    else
                    {
                        lineTemp = line;
                    }

                    // Copy the lineTemp
                    using (StreamWriter fileWriter = new StreamWriter(PathToWeatherFile + ".tmp", true, Encoding.Default))
                        fileWriter.WriteLine(lineTemp);
                }
            }

            //--
            #endregion "Create temp file"

            #region "Copy temp File"
            //-- Delete old config file
            File.Delete(PathToWeatherFile);
            //-- Recreate the config file from the temp one
            File.Copy(PathToWeatherFile + ".tmp", PathToWeatherFile);
            //--
            #endregion "Copy temp File"

            #region "Delete temp File"
            //-- Delete Temp File
            File.Delete(PathToWeatherFile + ".tmp");
            //--
            #endregion "Delete temp File"

            ReadWeather();
        }
        public void SaveWeatherData(int temperatureInt, int weatherImg)
        {
            // Create a new file 
            // - copy the content of config.ini in this new file
            // - modify the parameters required
            // - erase the config.ini file by the modified one
            int i = 0;
            string line;
            string firstPara;
            string lineTemp = "";

            #region "Create temp file"
            //--
            using (StreamReader fileReader = new StreamReader(PathToWeatherFile, Encoding.Default))
            {
                // read line by line 
                // - if line contain parameters to modify: modify line and copy it
                // - if not just copy
                while (((line = fileReader.ReadLine()) != null) && i < 255)
                {
                    i++;

                    firstPara = line[0].ToString();
                    for (int charI = 1; charI < 4; charI++)
                        firstPara += line[charI].ToString();

                    #region "Temperature"
                    //--
                    if (firstPara == "Temp")
                    {
                        int temperatureTemp = 0;

                        if (temperatureInt < 0)
                            temperatureTemp = 0 - temperatureInt;
                        else
                            temperatureTemp = temperatureInt;

                        if (temperatureTemp < 10)
                            lineTemp = "Temp = 0" + temperatureTemp;
                        else if (temperatureTemp < 100)
                            lineTemp = "Temp = " + temperatureTemp;
                    }
                    else if (firstPara == "TSig")
                    {
                        if (temperatureInt < 0)
                            lineTemp = "TSig = 1";
                        else
                            lineTemp = "TSig = 0";
                    }
                    //--
                    #endregion "Temperature"

                    #region "Weather"
                    //--
                    else if (firstPara == "Weat")
                    {
                        if (weatherImg < 10)
                            lineTemp = "Weat = 0" + weatherImg;
                        else if (weatherImg < 100)
                            lineTemp = "Weat = " + weatherImg;
                    }
                    //--
                    #endregion "Weather"

                    // else line
                    else
                    {
                        lineTemp = line;
                    }

                    // Copy the lineTemp
                    using (StreamWriter fileWriter = new StreamWriter(PathToWeatherFile + ".tmp", true, Encoding.Default))
                        fileWriter.WriteLine(lineTemp);
                }
            }

            //--
            #endregion "Create temp file"

            #region "Copy temp File"
            //-- Delete old config file
            File.Delete(PathToWeatherFile);
            //-- Recreate the config file from the temp one
            File.Copy(PathToWeatherFile + ".tmp", PathToWeatherFile);
            //--
            #endregion "Copy temp File"

            #region "Delete temp File"
            //-- Delete Temp File
            File.Delete(PathToWeatherFile + ".tmp");
            //--
            #endregion "Delete temp File"
        }
        //--
        public void UpdateWeatherData()
        {
            string urlWeatherDotCom_Search = "http://xoap.weather.com/weather/local/" + CityId
                    + "?cc=*&prod=xoap&par=" + WeatherID
                    + "&key=" + WeatherKey;

            try
            {
                XmlTextReader reader = new XmlTextReader(urlWeatherDotCom_Search);
                
                string strURI = "";
                string strName = "";

                int iconCount = 0;

                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        #region "element"
                        //--
                        case XmlNodeType.Element:
                            strURI = reader.NamespaceURI;
                            strName = reader.Name;
                                                        
                            if (reader.Name == "tmp")
                            {
                                try
                                {
                                    Temperature = Convert.ToInt32(reader.ReadInnerXml());
                                }
                                catch (Exception e)
                                {
                                    Temperature = 99;
                                }
                            } 
                            if (reader.Name == "icon" && iconCount == 0)
                            {
                                iconCount++;
                                try
                                {
                                    WeatherIcon = Convert.ToInt32(reader.ReadInnerXml());
                                }
                                catch (Exception e)
                                {
                                    WeatherIcon = 99;
                                }
                            }
                        break;
                        //--
                        #endregion "element"

                        default:
                        break;
                    }
                }
            }
            catch (XmlException e)
            {
                Log.Write("error occured: " + e.Message);
            }

            SaveWeatherData(Temperature, WeatherIcon);
        }
        //--
        #endregion "Methods"
    }
}
